package com.eshop.config.security.component;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 权限控制
 * 判断用户角色
 * @author guyongrui
 */

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) throws
            AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : configAttributes) {
            //当前访问的url所需要的角色
            String needRole = configAttribute.getAttribute();
//            System.out.println("当前请求的菜单url需要角色："+needRole);
            //判断角色为是否登录即可访问的角色，此角色再CustomFilter中设置
            if ("ROLE_LOGIN".equals(needRole)){
//                System.out.println("当前角色为： ROLE_LOGIN");
                //判断当前是否登录
                if(authentication instanceof AnonymousAuthenticationToken){
//                    System.out.println("尚未登陆！");
                    throw new AccessDeniedException("尚未登录，请登录");
                }else {
//                    System.out.println("已登陆且角色为ROLE_LOGIN，可返回！");
                    return;
                }
            }
            //判断用户角色是否为该url所需角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
//                System.out.println("当前用户authority："+authority);
                if (authority.getAuthority().equals(needRole)){
//                    System.out.println("角色匹配成功，可返回！");
                    return;
                }
            }
        }
//        System.out.println("权限不足，请联系管理员");
        throw new AccessDeniedException("权限不足，请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
